<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="40%" @ok="handleSubmit" :destroyOnClose="true">
    <BasicForm @register="registerForm"> </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { computed, ref, unref } from 'vue';
import { BasicForm, useForm } from '@apps/antd-admin/src/components/Form/index';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import { formSchema } from './data';
import { add, update } from './api';
// 声明Emits
const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);

const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  labelWidth: 90,
  schemas: formSchema,
  showActionButtonGroup: false,
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    setFieldsValue({
      ...data.record,
    });
  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增支付配置' : '编辑支付配置'));

async function handleSubmit() {
  try {
    const values = await validate();
    setDrawerProps({ confirmLoading: true });
    if (unref(isUpdate)) {
      await update(values);
    } else {
      await add(values);
    }
    console.log(values);
    closeDrawer();
    emit('success');
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
